package com.iyimo.loader
{
	import com.iyimo.event.LoadEvent;
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	[Event(name="LOAD_COMPLETE", type="com.iyimo.event.LoadEvent")]
	
	public class BaseLoader extends EventDispatcher{
		public function BaseLoader(){}
		
		/**
		 * 加载xml,txt之类的
		 */		
		public function loadXml(url:String):void{
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.load(new URLRequest(url));
			urlLoader.addEventListener(Event.COMPLETE, onXmlComplete);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
		}
		
		/**
		 * 加载swf
		 * 
		 */		
		public function loadSwf(url:String):void{
			var loader:Loader = new Loader();
			loader.load(new URLRequest(url));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
		}
		
		/**
		 * 加载xml完毕
		 * @param e
		 */		
		protected function onXmlComplete(e:Event):void{
			var ldr:URLLoader = e.currentTarget as URLLoader;
			sendFinishEvent(ldr.data);
			
			ldr.removeEventListener(Event.COMPLETE, onXmlComplete);
			ldr.removeEventListener(IOErrorEvent.IO_ERROR, onError);
		}
		
		/**
		 * 加载swf完毕
		 * @param e
		 */
		protected function onSwfComplete(e:Event):void{
			var info:LoaderInfo = e.target as LoaderInfo;
			sendFinishEvent(info.content);
			info.loader.unloadAndStop();
			
			info.removeEventListener(Event.COMPLETE, onXmlComplete);
			info.removeEventListener(IOErrorEvent.IO_ERROR, onError);
		}
		
		/**
		 * 加载错误
		 * @param e
		 */		
		protected function onError(e:IOErrorEvent):void{
			trace("BaseLoad", e.text);
		}
		
		/**
		 * 派发下载完毕
		 */		
		private function sendFinishEvent(data:Object):void{
			var e:LoadEvent = new LoadEvent(LoadEvent.COMPLETE);
			e.data = data;
			dispatchEvent(e);
		}
	}
}